package javaTest05.exercise01.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;

public class TcpServer {
    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(1024);
            System.out.println("服务端正在运行中...");
            Socket socket = server.accept();
            System.out.println("与客户端连接已成功建立,请求来自:" + socket.getRemoteSocketAddress()+" time:"+LocalDateTime.now());

            InputStream in = socket.getInputStream();
            saveFile(in, "src/javaTest05/resource/TcpRes.docx");
            System.out.println("文件传输成功");

            socket.close();
            server.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void saveFile(InputStream in, String path) {//将字节数组写入文件中
        FileOutputStream fOs = null;
        try {
            fOs = new FileOutputStream(path);
            byte[] buffer = new byte[1024];
            int count;
            while ((count = in.read(buffer)) != -1) {
                fOs.write(buffer, 0, count);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fOs != null) {
                    fOs.flush();
                    fOs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
